// pages/user_fuli_share/fulishare.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    logo: '',
    ratio: app.phoneInfo.ratio,
    alertType: false,
    second: 10,
    submitType: true,
    local_policy_id: '',
    disabled: true,
    name: '',
    phone: '',
    code: '',
    codeText: '获取验证码',
    isGetCode: true,
    codeColor: '#e63939',
    shareTempFilePath: '',
    showDialog: false,
    shareJson: {
      logo: '',
      wx_head: '',
      wx_name: '',
      start_date: '',
      end_date: '',
      money: 0,
      desc: '',
      id_number: 0
    }
  },

  setName: function (e) {
    if (e.detail.value && this.data.phone) {
      this.setData({
        disabled: false
      })
    } else {
      this.setData({
        disabled: true
      })
    }
    this.setData({
      name: e.detail.value
    })
  },

  setPhone: function (e) {
    if (e.detail.value && this.data.name) {
      this.setData({
        disabled: false
      })
    } else {
      this.setData({
        disabled: true
      })
    }
    this.setData({
      phone: e.detail.value
    })
  },

  // setCode: function (e) {
  //   if (e.detail.value && this.data.name && this.data.phone) {
  //     this.setData({
  //       disabled: false
  //     })
  //   } else {
  //     this.setData({
  //       disabled: true
  //     })
  //   }
  //   this.setData({
  //     code: e.detail.value
  //   })
  // },

  // getCode: function (e) {
  //   var that = this;
  //   if (!that.data.phone) {
  //     wx.showToast({
  //       title: '请填写手机号码',
  //       icon: 'none'
  //     });
  //     return;
  //   } else {
  //     if (!/^[1][345789][0-9]{9}$/.test(that.data.phone)) {
  //       wx.showToast({
  //         title: '手机号码格式不正确',
  //         icon: 'none'
  //       });
  //       return;
  //     }
  //   }
  //   if (that.data.isGetCode) {
  //     var second = 60;
  //     wx.request({
  //       url: app.globalData.url + 'c=message&m=getYzm&phone=' + that.data.phone,
  //       success: res => {
  //         wx.setStorageSync("sessionid", res.header["Set-Cookie"]);
  //         res = res.data;
  //         if (res.status === 200) {
  //           wx.showToast({
  //             title: '发送成功',
  //             icon: 'success'
  //           })
  //           that.setData({
  //             codeText: second + '秒后重发',
  //             codeColor: '#cccccc',
  //             isGetCode: false
  //           })
  //           var timer = setInterval(function () {
  //             second--;
  //             that.setData({
  //               codeText: second + '秒后重发'
  //             })
  //             if (second <= 0) {
  //               that.setData({
  //                 codeText: '获取验证码',
  //                 codeColor: '#e63939',
  //                 isGetCode: true
  //               })
  //               clearInterval(timer);
  //             }
  //           }, 1000)
  //         } else {
  //           wx.showToast({
  //             title: res.errMsg,
  //             icon: 'none'
  //           })
  //         }
  //       }
  //     })
  //   }
  // },
  
  submit() {
    var that = this;
    if (!this.data.name) {
      wx.showToast({
        title: '请填写姓名',
        icon: 'none'
      })
      return
    } else {
      if (/[^a-zA-Z0-9\_\u4e00-\u9fa5]+/i.test(this.data.name)) {
        wx.showToast({
          title: '姓名不得有非法字符',
          icon: 'none'
        });
        return
      }
    }
    if (!/^[1][3456789][0-9]{9}$/.test(this.data.phone)) {
      wx.showToast({
        title: '请填写正确的手机号码',
        icon: 'none'
      });
      return
    }
    // if (!this.data.code) {
    //   wx.showToast({
    //     title: '请填写验证码',
    //     icon: 'none'
    //   })
    //   return
    // }
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("sessionid")
      },
      url: app.globalData.url + 'c=policy&m=receivePolicy&user_id=' + wx.getStorageSync('user_id') + '&local_policy_id=' + that.data.local_policy_id + '&name=' + that.data.name + '&phone=' + that.data.phone,
      success: res => {
        res = res.data;
        if (res.status === 200) {
          that.setData({
            shareJson: {
              logo: res.data.logo,
              wx_head: res.data.wx_head,
              wx_name: res.data.agent_name,
              start_date: res.data.start_date,
              end_date: res.data.end_date,
              money: res.data.policy_money,
              desc: res.data.explain,
              id_number: res.data.id_number
            }
          });
          // that.getImage();

          //跳转到卡券
          wx.navigateTo({
            url: '/pages/guidanceStudy/fuli_caption/fulicaption?' +
              '&name=' + this.data.name +
              '&logo=' + this.data.shareJson.logo +
              '&wx_head=' + this.data.shareJson.wx_head +
              '&wx_name=' + this.data.shareJson.wx_name +
              '&start_date=' + this.data.shareJson.start_date +
              '&end_date=' + this.data.shareJson.end_date +
              '&money=' + this.data.shareJson.money + 
              '&id_number=' + this.data.shareJson.id_number +
              '&desc=' + this.data.shareJson.desc
          });
          wx.hideLoading();
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
          wx.hideLoading();
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      logo: options.logo,
      local_policy_id: options.local_policy_id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 获取图片
   */
  getImage: function () {
    wx.getImageInfo({
      src: this.data.shareJson.logo,
      success: img1 => {
        wx.getImageInfo({
          src: 'https://zsy.api.oucnet.com/statics/zsy/resourse/img/app_qrcode.png',
          success: img2 => {
            wx.getImageInfo({
              src: this.data.shareJson.wx_head,
              success: img3 => {
                // this.drawImg(img1, img2, img3);
               
              }
            })
          },
          fail: () => {
            wx.hideLoading();
          }
        })
      },
      fail: () => {
        wx.hideLoading();
      }
    });
  },

  /**
   * canvas绘制
   */
  drawImg: function (img1, img2, img3) {
    var context = wx.createCanvasContext('share');
    context.fillStyle = '#7b7b7b';
    context.fillRect(0, 0, 750 / this.data.ratio, 1334 / this.data.ratio);

    let canvasWidthPx = 620 / this.data.ratio;
    let canvasHeightPx = 1065 / this.data.ratio;
    context.drawImage("/images/fuli-share-bg.png", 65 / this.data.ratio, 67 / this.data.ratio, canvasWidthPx, canvasHeightPx);

    let img1X = (750 - img1.width) / this.data.ratio / 2;
    let img1Y = 115 / this.data.ratio;
    context.drawImage(img1.path, img1X, img1Y, img1.width / this.data.ratio, img1.height / this.data.ratio);

    context.setFontSize(72 / this.data.ratio);
    context.setTextAlign('right');
    context.setFillStyle('#ff3333');
    context.fillText(this.data.shareJson.money, 420 / this.data.ratio, 415 / this.data.ratio);

    let img2X = 262 / this.data.ratio;
    let img2Y = 513 / this.data.ratio;
    context.drawImage(img2.path, img2X, img2Y, 225 / this.data.ratio, 225 / this.data.ratio);

    context.setFontSize(24 / this.data.ratio);
    context.setTextAlign('left');
    context.setFillStyle('#666666');
    context.fillText('有效期：' + this.data.shareJson.start_date + ' - ' + this.data.shareJson.end_date, 100 / this.data.ratio, 890 / this.data.ratio);
    context.fillText('适用说明：' + this.data.shareJson.desc, 100 / this.data.ratio, 930 / this.data.ratio);

    context.save();
    context.beginPath();
    context.arc(174 / this.data.ratio, 1060 / this.data.ratio, 50 / this.data.ratio, 0, Math.PI * 2, false);
    context.setStrokeStyle('#e0e0e0');
    context.stroke();
    context.clip();
    context.drawImage(img3.path, 124 / this.data.ratio, 1010 / this.data.ratio, 100 / this.data.ratio, 100 / this.data.ratio);
    context.restore();

    context.setFontSize(32 / this.data.ratio);
    context.setTextAlign('left');
    context.setFillStyle('#ffffff');
    context.fillText('本优惠由' + this.data.shareJson.wx_name + '为你争取', 244 / this.data.ratio, 1050 / this.data.ratio);
    context.setFontSize(24 / this.data.ratio);
    context.fillText('顾问编号：' + this.data.shareJson.id_number, 244 / this.data.ratio, 1100 / this.data.ratio);

    context.draw(false, this.getTempFilePath);
  },

  /**
   * 获取临时路径
   */
  getTempFilePath: function () {
    wx.canvasToTempFilePath({
      canvasId: 'share',
      success: res => {
        this.setData({
          shareTempFilePath: res.tempFilePath
        })
        this.saveImageToPhotosAlbum();
      }
    })
  },

  /**
   * 保存相册
   */
  saveImageToPhotosAlbum: function () {
    wx.hideLoading();
    var that = this;
    if (!this.data.shareTempFilePath) {
      wx.showModal({
        title: '提示',
        content: '图片绘制中，请稍后重试',
        showCancel: false
      })
    }
    wx.getSetting({
      success(res) {
        console.log(res);
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.save();
            },
            fail(err) {
              console.log(err);
              that.setData({
                'showDialog': true
              })
            }
          })
        } else {
          that.save();
        }
      }
    })
  },

  save: function () {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareTempFilePath,
      success: (res) => {
        this.setData({
          alertType: true
        })
        this.waitTime();
      },
      fail: (err) => {
        console.log(err);
      }
    })
  },

  /**
   * 倒计时
   */
  waitTime: function () {
    let s = this.data.second;
    var timer = setInterval(() => {
      s--;
      if (s == 0) {
        clearInterval(timer);
        timer = null;
        this.setData({
          submitType: false
        })
      } else {
        this.setData({
          second: s
        });
      }
    }, 1000);

    // setTimeout(this.waitTime, 1000);
  },

  /**
   * 关闭弹窗
   */
  closeAlert: function () {
    this.setData({
      alertType: false,
      submitType: true,
      second: 10
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})